package com.ly.algorithm.offerpointer;

/**
 * @Classname Offer12
 * @Description
 *
 * 请设计一个函数，用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一格开始，每一步可以在矩阵中向左、右、上、下移动一格。如果一条路径经过了矩阵的某一格，那么该路径不能再次进入该格子。例如，在下面的3×4的矩阵中包含一条字符串“bfce”的路径（路径中的字母用加粗标出）。
 *
 * [["a","b","c","e"],
 * ["s","f","c","s"],
 * ["a","d","e","e"]]
 *
 * 但矩阵中不包含字符串“abfb”的路径，因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后，路径不能再次进入这个格子。
 *
 *  
 *
 * 示例 1：
 *
 * 输入：board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
 * 输出：true
 * 示例 2：
 *
 * 输入：board = [["a","b"],["c","d"]], word = "abcd"
 * 输出：false
 *
 *
 * @Date 2020/12/30 21:01
 * @Author 冷心影翼
 */
public class Offer12 {

    public static void main(String[] args) {
        Solution12 solution12 = new Solution12();
        char[][] board = new char[][] {
            {'A','B','C','E'},
            {'S','F','C','S'},
            {'A','D','E','E'}
        };
        System.out.println(solution12.exist(board, "ABCCE"));
    }

}

class Solution12 {
    public boolean exist(char[][] board, String word) {
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                if(exist(board,word,i,j,0)) {
                    return true;
                }
            }
        }
        return false;
    }

    public boolean exist(char[][] board, String word,int i,int j,int n) {
        if(n == word.length()) {
            return true;
        }
        if(i<0 || i>=board.length || j<0 || j>=board[0].length)
            return false;
        if(board[i][j] != word.charAt(n)) {
            return false;
        }
        char c = board[i][j];
        board[i][j] = '#';
        boolean res =  exist(board,word,i-1,j,n+1) || exist(board,word,i,j+1,n+1) ||
            exist(board,word,i+1,j,n+1) || exist(board,word,i,j-1,n+1);

        board[i][j] = c;

        return res;
    }
}